package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
	"vpn/app/global"
	"vpn/app/http/form_validate"
	"vpn/app/utils/openvpn"
	"vpn/app/utils/response"
)

func GetOpenvpnConfig(context *gin.Context) {
	file_path := global.OpenvpnConf.ConfigPath
	//test_file_path := "./test/service.conf"
	conf, err := openvpn.ReadConfig(file_path)
	if err != nil {
		log.Error("ReadOpenVPNConfig Fail")
		response.Fail(context, 500, "服务异常!", gin.H{"error": err.Error()})
		return
	}
	response.Success(context, "", gin.H{"ip": conf.Subnet, "mask": conf.Mask, "client_conn_enable": conf.ClientConnEnable})
}

func SaveOpenConfig(context *gin.Context) {
	defer func() {
		if p := recover(); p != nil {
			log.Error(fmt.Sprintf("SaveOpenConfig error: %v", p))
			response.Fail(context, 500, "保存失败，服务异常!", gin.H{"error": p})
			return
		}
	}()
	var vpnConfig form_validate.OpenVpnConfForm
	vpnConfig.ValidateVpnConfig(context)
	openvpn.SaveConf(vpnConfig.OpenVpnSubNet, vpnConfig.OpenVpnMask, vpnConfig.ClientConnEnable)
	response.Success(context, "openvpn配置保存成功！", gin.H{})
}

func InstallOpenvpnService(context *gin.Context) {
	defer func() {
		if p := recover(); p != nil {
			log.Error(fmt.Sprintf("InstallOpenvpnService error: %v", p))
			response.Fail(context, 500, "openvpn服务安装异常!", gin.H{"error": p})
			return
		}
	}()
	var vpnConfig form_validate.OpenVpnInstallConfForm
	vpnConfig.ValidateVpnConfig(context)
	openvpn.Install(vpnConfig.OpenVpnSubNet, vpnConfig.OpenVpnMask, vpnConfig.ClientConnEnable, vpnConfig.PassWord)
	response.Success(context, "openvpn服务安装成功！", gin.H{})
}

func ResetOpenvpnService(context *gin.Context) {
	openvpn.RemoveConf()
	InstallOpenvpnService(context)
}
